package com.example.pceb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.entity.Course;
import com.example.pceb.entity.Enrollment;
import com.example.pceb.mapper.EnrollmentMapper;
import com.example.pceb.result.Result;
import com.example.pceb.service.putCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/course")
public class CourseController {
    @Autowired
    private putCourseService courseService;

    @Autowired
    private EnrollmentMapper enrollmentMapper;

    // 发布课程
    @PostMapping("/add")
    public Result add(@RequestBody Course course) {
        courseService.addCourse(course);
        return Result.success("课程发布成功");
    }

    // 获取课程列表
    @GetMapping("/list")
    public Result<List<Course>> list() {
        System.out.println(courseService.getAllCourses());
        return Result.success(courseService.getAllCourses());
    }

    // 获取课程详情
    @GetMapping("/{id}")
    public Result<Course> get(@PathVariable Long id) {
        return Result.success(courseService.getCourseById(id));
    }

    // 获取选了某课程的所有学生 ID
    @GetMapping("/{id}/students")
    public Result<List<Long>> getEnrolledStudents(@PathVariable Long id) {
        List<Enrollment> enrollments = enrollmentMapper.selectList(
                new QueryWrapper<Enrollment>().eq("course_id", id));
        List<Long> studentIds = enrollments.stream()
                .map(Enrollment::getStudentId)
                .collect(Collectors.toList());
        return Result.success(studentIds);
    }

    //学生选课
    @PostMapping("/join")
    public Result join(@RequestParam Long studentId, @RequestParam Long courseId) {
        System.out.println("controller正常");
        courseService.enroll(studentId, courseId);
        return Result.success("选课成功");
    }

    //学生查看自己选了什么课
    @GetMapping("/student/{id}")
    public Result<List<Course>> getCourses(@PathVariable Long id) {
        System.out.println("controller正常");
        return Result.success(courseService.getCoursesByStudent(id));
    }

    // 根据企业ID获取其发布的课程
    @GetMapping("/enterprise/{enterpriseId}")
    public Result<List<Course>> getByEnterpriseId(@PathVariable Long enterpriseId) {
        System.out.println("OK");
        System.out.println(Result.success(courseService.getCoursesByEnterpriseId(enterpriseId))+"c返回正常");
        return Result.success(courseService.getCoursesByEnterpriseId(enterpriseId));
    }

}
